import axios from 'axios'
import store from '@/store'
import {
	exchangeTokenAPI
} from '@/api/user.js'

const request = axios.create({
	baseURL: 'api'
})

request.interceptors.request.use(function(config) {
		const {
			user
		} = store.state

		if (user && user.token) {
			config.headers.Authorization = `Bearer ${user.token}`
		}

		return config
	},
	function(error) {
		return Promise.reject(error)
	})


request.interceptors.response.use(
	config => {
		return config
	},
	async error => {
		const {
			user
		} = store.state

		if (error.response && error.response.status === 401 && user.refresh_token) {
			user.token = ''

			const {
				data: res
			} = await exchangeTokenAPI(user.refresh_token)

			const newToken = {
				token: res.data.token,
				refresh_token: user.refresh_token,
			}
			store.commit('setUser', newToken)

			return request(error.config)
		}
		return Promise.reject(error)
	}
)


export default request
